import {
  updateBuckets,
  startUpdateBuckets,
  selectBucket
} from '../actions/s3bucket';
import { selectAccount } from '../actions/s3account';
import { fetchKeys, updateKeys, checkKey, uncheckKey } from '../actions/s3key';
import { getS3Manager } from '../functions/S3Manager';

export function selectS3Bucket(dispatch, bucket, account, s3Manager) {
  dispatch(selectBucket(bucket));
  //   const s3Manager = getS3Manager(account);

  dispatch(fetchKeys());
  s3Manager.listOneLayerKeys(bucket, keys => {
    dispatch(updateKeys(keys, ''));
  });
}

export function selectNewAccount(dispatch, account, s3Manager) {
  dispatch(selectAccount(account));
  dispatch(startUpdateBuckets());
  //   const s3Manager = getS3Manager(account);
  s3Manager.listBuckets(bucketNames => {
    console.log('get s3 buckets for current account ' + account.name);
    console.log(bucketNames);

    dispatch(updateBuckets(bucketNames));

    if (account.defaultBucket) {
      console.log('defaultBucket ' + account.defaultBucket);
      selectS3Bucket(dispatch, account.defaultBucket, account,s3Manager);
    }
  });
}
